package com.quasar.hpatient.module.home_heartrate;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home_heartrate.HeartrateItemBean;
import com.quasar.hpatient.bean.home_inspection.CalendarBean;
import com.quasar.hpatient.bean.home_inspection.CalendarHTBean;
import com.quasar.hpatient.dialog.CalendarDialog;
import com.quasar.hpatient.module.home_daily.HomeDailyActivity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.DimenUtil;
import lib.quasar.widget.chart.ChartView;
import okhttp3.RequestBody;

/**
 * description: 首页 ==> 心率
 * created by kalu on 2018/4/25 22:23
 */
public class HeartratePresenter implements BasePresenter {

    private final LinkedList<HeartrateItemBean> mDatas = new LinkedList();

    void initTime(final HeartrateView view, TextView dates, TextView times) {

        if (null != dates) {
            view.setText(dates, getCalendar());
        }
        if (null != times) {
            view.setText(times, getMinuteLittle());
        }
    }

    void initList(final HeartrateView view, RecyclerView recycler, boolean mulit) {

        if (null == view || null == recycler) return;

        final BaseCommonAdapter<HeartrateItemBean> adapter = new BaseCommonAdapter<HeartrateItemBean>(mDatas, R.layout.activity_home_heartrate_type_child) {

            @Override
            protected void onNext(final RecyclerHolder holder, final HeartrateItemBean model, final int position) {

                view.setText(holder, R.id.home_heartrate_child_time, model.getLogtime(!mulit));
                view.setText(holder, R.id.home_heartrate_child_input, model.getRecord_value());
                view.setText(holder, R.id.home_heartrate_child_state, model.getState());
                view.setTextColor(holder, R.id.home_heartrate_child_state, model.getColor());

                holder.setOnClickListener(R.id.home_heartrate_child_input, v -> view.showInput(model.getRecord_value(), position));
                holder.setOnLongClickListener(v -> {
                    view.showDelete(position);
                    return true;
                }, R.id.home_heartrate_child_input, R.id.home_heartrate_child_time, R.id.home_heartrate_child_state);
            }
        };

        final RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(40));
        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_heartrate_type_head, null);
        head.setLayoutParams(params);
        adapter.addHead(head);

        // adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    final void schemelList(CalendarDialog dialog, String year, String month, String minDay, String maxDay) {

        final HashMap<String, Object> map = new HashMap<>();
        map.put(BEGIN_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, minDay));
        map.put(END_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, maxDay));
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_HEARTRATE);
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_9);

        final Observable observable = HttpClient.getSingleHolder().getHttpService().schemeHTList(params);

        request(observable, new OnModelAcceptChangeListener<List<CalendarHTBean>>() {
            @Override
            public void modelSucc(List<CalendarHTBean> list) {
                dialog.getCalendarView().setScheme(list);
            }
        });
    }

    void heartrateList(final HeartrateView view, ChartView chart, RecyclerView recycler, TextView dates, boolean mulit) {

        if (null == view || null == chart || null == recycler || null == dates) return;

        final String trim = dates.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            view.toast("时间格式不正确");
            return;
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.RECORD_DATE, getDate(trim));
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_HEARTRATE);

        if (mulit) {

            map.put(HttpParams.NUM, "10");
            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_3);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().heartrateListMulit(params);

            request(observable, new OnModelAcceptChangeListener<List<HashMap<String, ArrayList<HeartrateItemBean>>>>() {
                @Override
                public void modelFail() {
                    view.setChartNull(chart, R.string.chart_null);
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(List<HashMap<String, ArrayList<HeartrateItemBean>>> result) {

                    if (null == result || result.size() == 0) {
                        modelFail();
                        return;
                    }

                    for (HashMap<String, ArrayList<HeartrateItemBean>> map : result) {

                        if (null == map || map.size() == 0) continue;

                        final Collection<ArrayList<HeartrateItemBean>> collection = map.values();
                        if (null == collection || collection.size() == 0) continue;

                        for (ArrayList<HeartrateItemBean> list : collection) {

                            if (collection.size() == 1 && (null == list || list.size() == 0))
                                continue;

                            for (HeartrateItemBean model : list) {
                                if (collection.size() == 1 && list.size() == 1 && null == model)
                                    continue;
                                mDatas.add(model);
                            }
                        }
                        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                    }
                }

                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });

        } else {

            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_2);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().heartrateList(params);

            request(observable, new OnModelAcceptChangeListener<HashMap<String, ArrayList<HeartrateItemBean>>>() {
                @Override
                public void modelFail() {
                    view.setChartNull(chart, R.string.chart_null);
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(HashMap<String, ArrayList<HeartrateItemBean>> result) {

                    if (null == result) {
                        modelFail();
                        return;
                    }

                    final Collection<ArrayList<HeartrateItemBean>> collection = result.values();
                    if (null == collection || collection.size() == 0) {
                        modelFail();
                        return;
                    }

                    for (ArrayList<HeartrateItemBean> list : collection) {

                        if (collection.size() == 1 && (null == list || list.size() == 0)) {
                            modelFail();
                            return;
                        }

                        for (HeartrateItemBean model : list) {

                            if (collection.size() == 1 && list.size() == 1 && null == model) {
                                modelFail();
                                return;
                            }

                            mDatas.add(model);
                        }
                    }
                    Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                }

                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });
        }
    }

    void saveHeartrate(final HeartrateView view, ChartView chart, RecyclerView recycler, EditText edit) {

        if (null == view || null == chart || null == recycler || null == edit)
            return;

        final String dateStr = view.getDate();
        if (TextUtils.isEmpty(dateStr)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String timeStr = view.getTime();
        if (TextUtils.isEmpty(timeStr)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String rateStr = view.getHeartrate();
        if (TextUtils.isEmpty(rateStr)) {
            view.toast(R.string.home_heartrate_waining);
            edit.getText().clear();
            return;
        }

        final int num = Integer.parseInt(rateStr);
        if (num < 40 || num > 200) {
            view.toast(R.string.home_heartrate_waining);
            edit.getText().clear();
            return;
        }

        // step:1
        final HashMap<String, List<HeartrateItemBean>> map = new HashMap<>();
        final ArrayList<HeartrateItemBean> list = new ArrayList<>();
        // step:2
        final HeartrateItemBean news = new HeartrateItemBean();
        news.setRecord_datetime(getDate(dateStr, timeStr));
        news.setRecord_value(rateStr);
        final String itemdose = BaseApp.getResource().getString(R.string.home_heartrate_unit);
        news.setRecord_dose(itemdose);
        String warnSign = "0";
        mDatas.addFirst(news);
       // list.add(news);
        map.put(getDate(dateStr), list);
        // step:3

        for (HeartrateItemBean model : mDatas) {

            if ("0".equals(warnSign) && model.isWarning()) {
                warnSign = "1";
            }

            final String key = model.getKey();
            if (map.containsKey(key)) {
                final List<HeartrateItemBean> list1 = map.get(key);
                list1.add(model);
            } else {
                final List<HeartrateItemBean> list2 = new ArrayList<>();
                list2.add(model);
                map.put(key, list2);
            }
        }

        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));
        // step:4
        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(dateStr));
        params2.put(HttpParams.DATAS, map);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_HEARTRATE);
        params2.put(HttpParams.HT_WARN_SIGN, warnSign);

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveHeartrate(params1);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                view.toast("添加心率失败");
            }

            @Override
            public void modelSucc() {


                edit.getText().clear();
                edit.clearFocus();
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("添加心率成功");
            }

            @Override
            public void modelComplete() {
                view.clearInput();
            }
        });
    }

    void modefyHeartrate(final HeartrateView view, ChartView chart, RecyclerView recycler, String input, int position) {

        if (null == view || null == chart || null == recycler) return;

        if (TextUtils.isEmpty(input)) {
            view.toast(R.string.home_heartrate_waining);
            return;
        }

        final int num = Integer.parseInt(input);
        if (num < 40 || num > 200) {
            view.toast(R.string.home_heartrate_waining);
            return;
        }

        final HeartrateItemBean model = mDatas.get(position);
        final String old = model.getRecord_value();
        model.setRecord_value(input);

        // step:3
        String warnSign = "0";
        for (HeartrateItemBean temp : mDatas) {
            if ("0".equals(warnSign) && temp.isWarning()) {
                warnSign = "1";
            }
        }

        final HashMap<String, List<HeartrateItemBean>> push = new HashMap<>();
        push.put(getDate(view.getDate()), mDatas);
        final HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(view.getDate()));
        params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_HEARTRATE);
        params2.put(HttpParams.HT_WARN_SIGN, warnSign);

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveHeartrate(params1);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                model.setRecord_value(old);
                view.toast("修改心率失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("修改心率成功");
            }
        });
    }

    void deleteHeartrate(final HeartrateView view, ChartView chart, RecyclerView recycler, int position) {

        if (null == view || null == chart || null == recycler) return;

        final HeartrateItemBean delete = mDatas.get(position);
        mDatas.remove(position);

        // step:3
        String warnSign = "0";
        for (HeartrateItemBean temp : mDatas) {
            if ("0".equals(warnSign) && temp.isWarning()) {
                warnSign = "1";
            }
        }
        final HashMap<String, List<HeartrateItemBean>> push = new HashMap<>();
        push.put(getDate(view.getDate()), mDatas);
        final HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(view.getDate()));
        if (mDatas.size() == 0)
            params2.put(HttpParams.DATAS, "");
        else
            params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_HEARTRATE);
        params2.put(HttpParams.HT_WARN_SIGN, warnSign);

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveHeartrate(params1);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                mDatas.add(position, delete);
                view.toast("删除心率失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("删除心率成功");
            }
        });
    }

    void caluState(final HeartrateView view, TextView state, String str) {

        String result;
        int color;
        Context context = BaseApp.getContext();

        try {
            float temp = Float.parseFloat(str);

            // 1. ＜59.9为心率过缓
            if (temp <= 59.9f) {
                result = "心率过缓";
                color = context.getResources().getColor(R.color.color_bg_peach);
            }
            // 2.60——100为正常
            else if (temp >= 60f && temp <= 100f) {
                result = "正常";
                color = context.getResources().getColor(R.color.color_bg_theme);
            }
            // 3.＞100.1为心率过速
            else {
                result = "心率过速";
                color = context.getResources().getColor(R.color.color_bg_peach);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "异常数值";
            color = context.getResources().getColor(R.color.color_bg_peach);
        }

        view.setText(state, result);
        view.setTextColor(state, color);
    }

    Intent getResult(HeartrateView view, int position) {

        if (position != -1 && mDatas.size() != 0) {
            final Intent intent = new Intent();
            intent.putExtra(HomeDailyActivity.POSITION, position);
            final HeartrateItemBean model = mDatas.get(0);
            final int value = Float.valueOf(model.getValue()).intValue();
            intent.putExtra(HomeDailyActivity.INPUT, String.valueOf(value));
            return intent;
        }
        return null;
    }

    @Override
    public void recycler() {
    }
}
